package cn.test.word.ex;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.test.word.MainTest;
import cn.test.word.ex.RenderFunction;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.policy.AbstractRenderPolicy;
import com.deepoove.poi.render.RenderContext;
import com.deepoove.poi.render.compute.RenderDataCompute;
import com.deepoove.poi.template.ElementTemplate;
import com.deepoove.poi.template.run.RunTemplate;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class StrongRenderPolicy extends AbstractRenderPolicy<Object> {
    private Map<String, RenderFunction> functionMap;

    public StrongRenderPolicy(Map<String, RenderFunction> functionMap) {
        this.functionMap = functionMap;
    }

    @Override
    public void render(ElementTemplate eleTemplate, Object data, XWPFTemplate template) {
        RenderDataCompute renderDataCompute = template.getConfig().getRenderDataComputeFactory().newCompute(MainTest.threadLocal.get());
        XWPFRun run = ((RunTemplate) eleTemplate).getRun();
        String placeHoder = run.toString();
        logger.info("placeHoder is {}", placeHoder);
        if (StringUtils.isBlank(placeHoder)) {
            run.setText("", 0);
            return;
        }
        String result = "";
        String functionStr = "doNothing";
        // 获取${%( 中间的函数字符串
        String pattern = "\\$\\{#(.*?)\\((.*)\\)";
        // 创建 Pattern 对象
        Pattern r = Pattern.compile(pattern);
        // 现在创建 matcher 对象
        Matcher m = r.matcher(placeHoder);
        if (m.find()) {
            functionStr = m.group(1);
        } else {
            throw new RuntimeException("[" + placeHoder + "]表达式不符合规则,请按照${%function(var,var2,var3)}格式");
        }
        RenderFunction rf = functionMap.get(functionStr);
        if (rf == null) {
            throw new RuntimeException(String.format("不支持的函数%s", functionStr));
        }

        String vars = m.group(2);
        //   CheckUtil.checkExpression(StringUtils.isNotEmpty(vars), "表达式不符合规则,请按照${%function(var,var2,var3)}格式");
        result = rf.doCalculate(vars.split(","), renderDataCompute);
        if (result == null || result.equals("null")) {
            run.setText("", 0);
            return;
        }
        run.setText(result, 0);
    }

    @Override
    public void doRender(RenderContext<Object> context) throws Exception {

    }

    @Override
    protected void afterRender(RenderContext<Object> context) {
        // 清空标签
        clearPlaceholder(context, true);
    }

    @Override
    protected void beforeRender(RenderContext<Object> context) {
        // 清空标签
        clearPlaceholder(context, true);
    }
}